package background
{
    import flash.display.Shape;
    import flash.events.Event;
    import flash.geom.Point;
    import flash.utils.getTimer;

    public class Snowflake extends Shape
    {
        private static const PERIOD     : Number = 1000.0;
        private static const FALL_SPEED : Number = 20.0;
        private static const EPS        : Number = 10.0;
        
        private var x_limit   : Number;
        private var y_limit   : Number;

        private var x_base    : Number;     
        private var angle     : Number;
        
        private var size      : Number;
        private var phase     : Number;
        private var amp       : Number;
        private var speed     : Number;
        
        private var startTime : Number;
        
        private var lastFrameTime : Number;
        
        public function Snowflake(_x_limit : int, _y_limit : int)
        {
            super();

            x_limit = _x_limit;
            y_limit = _y_limit; 

            addEventListener(Event.ENTER_FRAME, onEnterFrame);
            
            createRandomFlake(y = y_limit * Math.random());            
            
            
            startTime = flash.utils.getTimer();
            lastFrameTime = flash.utils.getTimer();
        }
        
        private function createRandomFlake(y_pos : Number) : void
        {
            size  = 1.0 + 3.0 * Math.random();
            phase = 2.0 * Math.PI * Math.random();
            amp   = 1.0 + Math.random() * size;
            speed = 50.0;//10.0 * size;

            graphics.clear();
            graphics.beginFill(0xDDDDFF);
            graphics.drawCircle(0, 0, size);
            graphics.endFill();

            x_base = x_limit * Math.random();
            angle = 0;

            x = x_base + amp * Math.sin(phase + angle);
            y = y_pos;
        }
        
        private function recreateAtTop() : void
        {
            createRandomFlake((y - size - EPS) - y_limit - size);
        }

        private function recreateAtBottom() : void
        {
            createRandomFlake((y + size + EPS) + y_limit + size);
        }
        
        private function onEnterFrame(event : Event) : void
        {
            const frameTime : Number = flash.utils.getTimer();
            const dt        : Number = frameTime - lastFrameTime;
            lastFrameTime = frameTime;
            
            angle += 2.0 * Math.PI * dt / PERIOD;
            x = x_base + amp * Math.sin(phase + angle);
            y += dt * speed / 1000;
            
            var p : Point = localToGlobal(new Point(0, 0));
            
            if(p.y - size > y_limit + EPS)
                recreateAtTop();
            if(p.y + size < -EPS)
                recreateAtBottom();
        }
    }
}